/*
 * @Author: jingzi 1163478123@qq.com
 * @Date: 2025-04-29 20:25:42
 * @LastEditors: jingzi 1163478123@qq.com
 * @LastEditTime: 2025-07-15 16:17:11
 * @Description: 页面处理
 * Copyright (c) 2025 by ${git_name}, All Rights Reserved.
 */
import '../gitlab/index.js'
import { copyToClipboard, getStorageData, setStorageData } from '../utils/index.js'
import { Toast } from '../utils/toast.js'

(function () {
  // 自动选中环境和项目
  const projectHandle = ({ projectName, tag }) => {
    const parameters = document.querySelector(".parameters");
    const parameterItem = parameters?.querySelectorAll(".jenkins-form-item");
    parameterItem.forEach(item => {
      const label = item.querySelector("input").value
      if(projectName.includes('erp-web')) {
        return
      }
      const changeEnvProject = ['cj-web-egg','mycj-react','cj-web-mobile','cj-web-mobile-react', 'chat'] // 需要切换环境的项目
      if(['environment','cluster'].includes(label) && changeEnvProject.includes(projectName)) {
        const select = item.querySelector(".jenkins-select__input")
        if(tag.includes('-cn') || tag.includes('_cn_')) {
          select.value = 'cn'
        } else {
          select.value = 'com'
        }
        const changeEvent = new Event('change', { bubbles: true });
        select.dispatchEvent(changeEvent);
      }
    })
    setTimeout(()=>{
      parameterItem.forEach(item => {
        const label = item.querySelector("input").value
        if (label.includes('new_projects')) {
          const checkbox = item.querySelector(".dynamic_checkbox")
          const input = checkbox?.querySelectorAll("input")
          input?.forEach(item=>{
            if(['cj-web-egg','mycj-react'].includes(projectName)) {
              if(!item.value.includes('1688')) {
                item.click()
              }
            }else{
              item.click()
            }
          })
        }
      })
    },1000)
  }
  
  const jenkinsHandle = ({ projectName, tag }) => {
    // 获取tag输入框并自动填入
    setTimeout(() => {
      const tagInput = document.querySelector(".git_parameter_quick_filter");
      if (tagInput) {
        // 设置输入值
        tagInput.value = tag;
        
        // 创建并触发 input 事件
        const inputEvent = new Event('input', { bubbles: true });
        tagInput.dispatchEvent(inputEvent);
        
        // 创建并触发 change 事件
        const changeEvent = new Event('change', { bubbles: true });
        tagInput.dispatchEvent(changeEvent);
        
        // 创建并触发 keyup 事件
        const keyupEvent = new KeyboardEvent('keyup', {
          bubbles: true,
          key: 'Enter',
          keyCode: 13
        });
        tagInput.dispatchEvent(keyupEvent);
        
        // 根据tag判断是哪个项目，并选中方法及其环境
        projectHandle({ projectName, tag })
      } else {
        console.error('Tag input element not found');
      }
    }, 1000);
  };
  // 清除选中项目
  const clearSelectedProject = () => {
    const parameters = document.querySelector(".parameters");
    const parameterItem = parameters?.querySelectorAll(".jenkins-form-item");
    parameterItem.forEach(item => {
      const label = item.querySelector("input").value
      if (label.includes('new_projects')) {
        const checkbox = item.querySelector(".dynamic_checkbox")
        const input = checkbox?.querySelectorAll("input")
        input?.forEach(item=>{
          item.click()
        })
      }
    })
  }
  // 一键多选项目
  const selectedAllProject = () => {
    const parameters = document.querySelector(".parameters");
    const parameterItem = parameters?.querySelectorAll(".jenkins-form-item");
    parameterItem.forEach(item => {
      const label = item.querySelector("input").value
      if (label.includes('new_projects')) {
        const checkbox = item.querySelector(".dynamic_checkbox")
        const input = checkbox?.querySelectorAll("input")
        input?.forEach(item=>{
          item.click()
        })
      }
    })
  }
  // 获取jira信息
  const getJiraInfo = () => {
    const jiraInfo = document.querySelector('.aui-toolbar2-primary')
    const COPYBTN = `<button class="copy-btn" id="copyBtn">复制jira信息</button>`
    const jiraTitle = document.title
    const jiraUrl = location.href
    jiraInfo && jiraInfo.insertAdjacentHTML('afterend',COPYBTN)
    const copyBtn = document.getElementById('copyBtn')
    copyBtn.addEventListener('click',()=>{
      copyToClipboard(`${jiraTitle} ${jiraUrl}`)
      Toast.success(`${jiraTitle}信息复制成功`)
    })
  }
  // 页面加载的方法
  const handlePageLoad = async () => {
    console.log("Content script loaded");
    if(location.href.includes('jira.cjdropshipping.cn')) {
      getJiraInfo()
    }
    if (location.href.includes('online.jk.com')) {
      const selectedElements = await getStorageData('selectedElementData') || []
      const { projectName, tag, time } = selectedElements[0];
      jenkinsHandle({ projectName, tag, time });
    }
    // 监听来自popup的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      console.log("Received message:", request);

      if (request.action === "selectAll") {
        try {
          if (!location.href.includes("192.168.5.143")) {
            sendResponse({ success: false, message: "当前页面不是gitlab页面" });
            return true;
          }
          const project = document
            .querySelector(".js-breadcrumbs-list")
            .querySelectorAll("li");
          const projectName = project[project.length - 2].textContent;
          // 获取Jenkins页面中的特定元素
          const contentBody = document.getElementById("content-body");
          // 获取第一个flex-row节点
          const flexRow = contentBody.querySelector(".flex-row");
          const tag = flexRow.querySelector(".item-title").textContent;
          const time = flexRow.querySelector(".js-timeago-render").textContent;

          // 高亮显示该元素
          flexRow.style.border = "2px solid red";
          flexRow.style.backgroundColor = "rgba(255, 0, 0, 0.1)";

          // 存储找到的数据
          const elementData = {
            projectName,
            tag,
            time,
          };

          setStorageData('selectedElementData', elementData)

          sendResponse({
            success: true,
            message: "Element found and highlighted",
            data: elementData,
          });
        } catch (error) {
          console.error("Error in content script:", error);
          sendResponse({ success: false, message: error.message });
        }
      }
      if (request.action === "clearCheckProject") {
        clearSelectedProject()
      }
      if (request.action === "selectedAllProject") {
        selectedAllProject()
      }
      return true; // 保持消息通道开放
    });
  };
  // 在页面加载完成时执行
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', handlePageLoad);
  } else {
    handlePageLoad();
  }
})();
